<route lang="json5" type="page">
{
  layout: "base",
  style: {
    navigationBarTitleText: "活动报名",
  },
}
</route>

<template>
  <view class="page-eventRegistrations">
    <view class="content-title">
      <uni-easyinput
        :inputBorder="false"
        maxlength="40"
        class="uni-mt-5"
        trim="all"
        v-model="model.title"
        placeholder="请输入活动标题"
      ></uni-easyinput>
      <view class="text-count">{{ model.title.length }}/40</view>
    </view>
    <view class="content-desc">
      <view class="box">
        <view class="toolbar">
          <uni-icons
            @click="handleInsertImage"
            type="image-filled"
            color="#bfbfbf"
            size="36"
          ></uni-icons>
          <button @click="handleFontSize('正')">正</button>
          <button @click="handleFontSize('大', 'bold')">大</button>
          <button @click="handleFontSize('中', 'bold')">中</button>
          <button @click="handleFontSize('小', 'bold')">小</button>
        </view>
        <editor
          id="editor"
          :show-img-toolbar="true"
          :show-img-resize="true"
          :show-img-size="true"
          class="ql-container container"
          placeholder="请尽情发挥吧..."
          @input="richText"
          @ready="onEditorReady"
        ></editor>
      </view>
    </view>
    <!--    <view class="img-up">-->
    <!--      <image-upload-->
    <!--          max="9"-->
    <!--          :mediaType="['image']"-->
    <!--          text="上传图片"-->
    <!--          :imgs="model.imgs"-->
    <!--          @delete-images-fun="deleteImagesFun"-->
    <!--          @select-handle="avatarSelectHandle"-->
    <!--      ></image-upload>-->
    <!--    </view>-->

    <view class="content-cover">
      <image-upload
        max="9"
        :mediaType="['image']"
        text="添加封面"
        :imgs="model.cover"
        @delete-images-fun="deleteCoverFun"
        @select-handle="coverSelectHandle"
      ></image-upload>
    </view>
    <view class="video-up">
      <image-upload
        max="9"
        :mediaType="['video']"
        text="上传视频"
        :imgs="model.videos"
        @delete-images-fun="deleteVideoFun"
        @select-handle="videoSelectHandle"
      ></image-upload>
    </view>
    <view>
      <uni-popup ref="inputDialog" type="dialog">
        <uni-popup-dialog
          ref="inputClose"
          mode="input"
          title="添加标签"
          placeholder="请输入标签内容"
          @confirm="dialogInputConfirm"
        ></uni-popup-dialog>
      </uni-popup>
    </view>
    <view class="bottom-flex">
      <view @click="submit" class="bottom-flex-btn">发布</view>
    </view>
  </view>
</template>

<script lang="ts" setup>
import { ref } from "vue";
import {
  addCompositionAndRegister,
  editCompositionAndRegister,
  getCompositionAndRegister,
} from "@/service/aboutAdd";
import ImageUpload from "@/components/upload-new/index.vue";
import { getFileExtension } from "@/utils";
const VITE_UPLOAD_BASEURL = import.meta.env.VITE_UPLOAD_BASEURL;
import { storeToRefs } from "pinia";
import { useUserStore } from "@/store";
const userStore = useUserStore();
const { userInfo } = storeToRefs(userStore);
let editorCtx;
const inputDialog = ref(null);
let activityId = "";
const id = null;

const model = reactive<{
  title: string;
  content: string;
  cover: any[];
  videos: any[];
}>({
  title: "",
  content: "",
  cover: [],
  videos: [],
});
let editorValue;

const tags = reactive({
  addTagValue: "",
  list: [
    "社群作品",
    "社群任务发布",
    "社群交流",
    "社群作品1",
    "社群任务发布1",
    "社群交流1",
  ],
});

onLoad((e: any) => {
  if (e?.activityId) {
    activityId = e?.activityId;
  }
  if (e?.id) {
    getDetail();
  }
});

const getDetail = async () => {
  const res = await getCompositionAndRegister(id);
};

const addTagFun = () => {
  inputDialog.value.open();
};
// tags
const dialogInputConfirm = (e) => {
  tags.addTagValue = e;
  tags.list.push(e);
};
// 删除tag
const deleteTag = (value) => {
  tags.list = tags.list.filter((item) => item !== value);
};

const onEditorReady = () => {
  uni
    .createSelectorQuery()
    .select("#editor")
    .context(function (res) {
      editorCtx = res?.context;
    })
    .exec();
};
const handleFontSize = (type, isBold) => {
  if (isBold) {
    editorCtx.format("bold");
  }
  if (type === "正") {
    editorCtx.format("font-size", "12px");
  } else if (type === "大") {
    editorCtx.format("font-size", "26px");
  } else if (type === "中") {
    editorCtx.format("font-size", "20px");
  } else if (type === "小") {
    editorCtx.format("font-size", "16px");
  }
};
//插入图片
const handleInsertImage = () => {
  uni.chooseImage({
    count: 1, //插图图片数量
    sizeType: ["original", "compressed"], //可以指定是原图还是压缩图，默认二者都有
    sourceType: ["album", "camera"], //从相册选择和拍照
    success: function (res) {
      let linkUrl = "";
      uni.uploadFile({
        url: VITE_UPLOAD_BASEURL,
        name: "file",
        filePath: res.tempFilePaths[0],
        header: {
          "content-type": "multipart/form-data",
        },
        success: (res: any) => {
          const data = JSON.parse(res.data);
          linkUrl = data.data.link;
          editorCtx.insertImage({
            src: data.data.link,
            width: "100%",
            height: "100%",
            success: function (res) {
              console.log("成功插入图片");
            },
            fail: function (res) {
              console.log("插入图片失败");
            },
          });
        },
        fail: (fail) => {
          console.log(fail);
        },
      });
    },
  });
};
const richText = (e) => {
  editorValue = e.target.html;
};
const submit = async () => {
  const data = <any>{
    title: model.title,
    description: editorValue,
    userId: userInfo.value.userId,
    coverImage: model?.cover?.map((item) => item?.url)?.join(),
    videoUrl: model?.videos?.map((item) => item?.url)?.join(),
    activityId,
  };
  if (id) {
    data.id = id;
  }
  if (!data.coverImage) {
    uni.showToast({
      icon: "none",
      title: "请上传封面",
    });
    return;
  }
  const res = id
    ? await editCompositionAndRegister(data)
    : await addCompositionAndRegister(data);
  if (res?.code === 200) {
    uni.showToast({
      icon: "success",
      title: "报名成功",
    });
    uni.navigateBack({ delta: 1 });
  }
};
const videoSelectHandle = (e) => {
  uploadOss(e, "videos");
};
// 删除图片
const deleteVideoFun = (index) => {
  model.videos.splice(index, 1);
};
// 上传封面
const coverSelectHandle = (e) => {
  uploadOss(e, "cover");
};
// 删除封面
const deleteCoverFun = (index) => {
  model.cover.splice(index, 1);
};
let isUploading = false; // 全局标记防止重复上传

const uploadOss = async (e, key) => {
  if (isUploading) return;
  isUploading = true;
  try {
    uni.showLoading({ title: "正在上传" });

    const uploadPromises = e.tempFiles.map((image) => {
      return new Promise((resolve, reject) => {
        uni.uploadFile({
          url: VITE_UPLOAD_BASEURL,
          name: "file",
          filePath: image.tempFilePath,
          header: { "content-type": "multipart/form-data" },
          success: (res) => {
            try {
              const data = JSON.parse(res.data);
              const extname = getFileExtension(data.data.name);
              // 使用响应式更新方法（假设 model 是 reactive 对象）
              model[key].push({
                name: data.data.name,
                extname,
                url: data.data.link,
              });
              resolve(res);
            } catch (parseError) {
              reject(parseError); // 处理 JSON 解析错误
            }
          },
          fail: (err) => {
            reject(err);
          },
        });
      });
    });

    await Promise.all(uploadPromises);
    uni.showToast({ title: "上传成功", icon: "success" });
  } catch (error) {
    uni.showToast({ title: "上传失败", icon: "error" });
  } finally {
    uni.hideLoading();
    isUploading = false;
  }
};
</script>

<style lang="scss" scoped>
.page-eventRegistrations {
  padding-bottom: 230rpx;
  width: 100%;
  .content-cover {
    width: 100%;
    padding: 0 24rpx;
    box-sizing: border-box;
  }
  .content-tag {
    width: 100%;
    height: 60 rpx;
    background: #ffffff;
    display: flex;
    box-sizing: border-box;
    padding: 0 24rpx;
    box-sizing: border-box;
    margin-top: 36rpx;

    .content-tag-list {
      height: 60rpx;
      flex-grow: 1;
      overflow-x: scroll;
      white-space: nowrap;
    }
    .content-tag-list-item {
      display: inline-block;
      height: 42rpx;
      background: #eeeeee;
      margin-right: 12rpx;
      font-size: 24rpx;
      text-align: center;
      line-height: 42rpx;
      box-sizing: border-box;
      border-radius: 6rpx;
      padding: 0rpx 36rpx 0rpx 16rpx;
      margin-top: 8rpx;
      position: relative;
    }
    .icon-delete {
      position: absolute;
      top: 0rpx;
      right: 6rpx;
    }

    .content-tag-add {
      width: 60rpx;
      height: 60rpx;
      font-size: 28rpx;
      text-align: center;
      line-height: 60rpx;
      background: #fff;
      box-shadow: -60rpx 0rpx 80rpx 1rpx rgba(0, 0, 0, 0.1);
    }
  }
  .content-title {
    box-sizing: border-box;
    overflow: hidden;
    height: 100rpx;
    padding-top: 16rpx;
    padding-left: 14rpx;
    padding-right: 24rpx;
    position: relative;
    background: #ffffff;
  }
  .text-count {
    position: absolute;
    width: 60rpx;
    height: 100rpx;
    top: 0;
    right: 26rpx;
    line-height: 100rpx;
    background: #ffffff;
    color: #bfbfbf;
    font-size: 12px;
  }
  .content-desc {
    width: 100%;
    height: 680rpx;
    //border-bottom: 1px solid #eeeeee;
  }
  .img-up,
  .video-up {
    padding: 0 24rpx;
  }
  .bottom-flex {
    width: 100%;
    height: 210rpx;
    position: fixed;
    left: 0;
    bottom: 0;
    box-shadow: 0rpx 0rpx 30rpx rgba(0, 0, 0, 0.1);
    background: #ffffff;
    .bottom-flex-btn {
      width: 622rpx;
      height: 104rpx;
      margin: 0 auto;
      border-radius: 100rpx;
      background: rgb(191, 231, 121);
      text-align: center;
      line-height: 104rpx;
      margin-top: 60rpx;
    }
  }
}
.box {
  width: 100vw;
  height: 300rpx;
  display: flex;
  flex: 1;
  flex-direction: column;
  background-color: #ffffff;
  .toolbar {
    padding: 0 20rpx;
    display: flex;
    flex-wrap: wrap;
    padding-top: 16rpx;
    border-top: 1px solid #eeeeee;
    border-bottom: 1px solid #eeeeee;
    button {
      min-width: 96rpx;
      font-size: 28rpx;
      margin-bottom: 16rpx;
    }
  }
  .container {
    display: flex;
    flex: 0.97;
    background-color: #fff;
    padding: 0 20rpx;
    padding-top: 8rpx;
  }
}
</style>
